<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="申请时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="流程状态" prop="processStatus">
        <el-select
          v-model="queryParams.processStatus"
          placeholder="请选择流程状态"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.BK_BOOK_APPLY_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="申请人" prop="applyUid">
        <el-select
          v-model="queryParams.applyUid"
          placeholder="请选择申请人"
          clearable
          filterable
          remote
          :remote-method="searchUsers"
          :loading="userLoading"
          class="!w-240px"
        >
          <el-option
            v-for="user in userList"
            :key="user.id"
            :label="user.nickname || user.name"
            :value="user.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px"/>
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px"/>
          重置
        </el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['bk:lw-book-out-apply:create']"
        >
          <Icon icon="ep:plus" class="mr-5px"/>
          新增
        </el-button>
        <el-button
          type="warning"
          plain
          @click="handleImport"
          v-hasPermi="['bk:lw-book-out-apply:import']"
        >
          <Icon icon="ep:upload" class="mr-5px"/>
          导入
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['bk:lw-book-out-apply:export']"
        >
          <Icon icon="ep:download" class="mr-5px"/>
          导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true"
              class="tableData">
      <el-table-column label="编号" align="center" prop="id"  width="80px"/>
      <el-table-column label="申请人" align="center" prop="applyName"  width="100px"/>
      <el-table-column label="流程状态" align="center" prop="processStatus"  width="100px">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.BK_BOOK_APPLY_STATUS" :value="scope.row.processStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="书籍清单" align="center" prop="processStatus"  width="240px">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openBooks( scope.row)"
          >
            {{ scope.row.books && scope.row.books.length > 0 ? (scope.row.books.length === 1 ? `《${scope.row.books[0].title}》` : `《${scope.row.books[0].title}》等`) : '查看' }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="数量" align="center" width="70px">
            <template #default="scope">
            {{ scope.row.books.length }}本
            </template>
          </el-table-column>
      <el-table-column label="审核人" align="center" prop="initialReviewName"/>
      <el-table-column label="审核说明" align="center" prop="initialReviewDes"/>
      <el-table-column label="备注" align="center" prop="remark"/>
      <el-table-column
        label="申请时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="160px"
      />
      <el-table-column label="操作" align="center" min-width="120px">
        <template #default="scope">
<!--          <el-button-->
<!--            link-->
<!--            type="primary"-->
<!--            @click="openForm('update', scope.row.id)"-->
<!--            v-hasPermi="['bk:lw-book-out-apply:update']"-->
<!--          >-->
<!--            编辑-->
<!--          </el-button>-->
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['bk:lw-book-out-apply:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <LwBookOutApplyForm ref="formRef" @success="getList"/>

  <!-- 漂入初审 -->
  <Dialog title="漂入审核" v-model="examineShow" width="500px">
    <el-form
      ref="formRef"
      :model="examineForm"
      label-width="40px"
      v-loading="formLoading"
    >
      <el-form-item label="结果" prop="title">
        <el-radio-group v-model="examineForm.audit">
          <el-radio key="0" value="0"><span style="color: #409eff">通 过</span></el-radio>
          <el-radio key="1" value="1"><span style="color: #ff6e6e">驳 回</span></el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="说明" prop="title">
        <el-input type="textarea" v-model="examineForm.des" placeholder="请输入说明，驳回时必填"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitExamine" type="primary" :disabled="formLoading">提 交</el-button>
      <el-button @click="closeExamine">取 消</el-button>
    </template>
  </Dialog>
  <!-- 书籍列表 -->
  <Dialog title="书籍列表" v-model="booksShow" width="1200px">
    <el-table v-loading="bookLoading" :data="bookList" :stripe="true" :show-overflow-tooltip="true"
              class="tableData">
      <el-table-column label="书名" align="center" prop="title" />
      <el-table-column label="isbn" align="center" prop="isbn"/>
      <el-table-column label="出版社" align="left" prop="publisher" width="210">
        <template #default="scope">
          <span>{{ scope.row.publisher }}</span>
          <el-tag v-if="scope.row.compliance" size="small" class="ml-2">合规</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="出版时间"
        align="center"
        prop="pubDate"
        :formatter="dateFormatter2"
        width="100px"
      />
      <el-table-column label="页数" align="center" prop="pageCount" />
      <el-table-column label="书籍状态" align="center" prop="storeStatus">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.BK_BOOK_STORE_STATUS" :value="scope.row.storeStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="当前持有" align="center" prop="nowHolderName"/>
      <el-table-column label="备注" align="center" prop="remark"/>
    </el-table>
  </Dialog>

  <!-- 表单弹窗：添加/修改 -->
  <LwBookOutApplyForm ref="formRef" @success="getList"/>
  <!-- 导入弹窗 -->
  <LwBookOutApplyImportForm ref="importFormRef" @success="getList"/>
</template>

<script setup lang="ts">
import {getIntDictOptions, DICT_TYPE} from '@/utils/dict'
import download from '@/utils/download'
import {LwBookOutApplyApi, LwBookOutApplyVO} from '@/api/bk/lwbookoutapply'
import LwBookOutApplyForm from './LwBookOutApplyForm.vue'
import LwBookOutApplyImportForm from './LwBookOutApplyImportForm.vue'
import {LwBookVO} from "@/api/bk/lwbook";
import {dateFormatter, dateFormatter2} from '@/utils/formatTime';
import * as MemberUserApi from '@/api/member/user'

/** 书籍漂出 列表 */
defineOptions({name: 'LwBookOutApplyHi'})

const message = useMessage() // 消息弹窗
const {t} = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<LwBookOutApplyVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const userList = ref<MemberUserApi.UserVO[]>([]) // 用户列表
const userLoading = ref(false) // 用户搜索加载中
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  createTime: [],
  applyUid: undefined,
  processStatus: undefined,
  processList:[-1,100],
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
/** 审核相关 */
const examineShow = ref(false)
const formLoading = ref(false)
const examineForm = reactive({
  applyId: undefined,
  audit: '0',
  des: undefined,
  auditType: 0,
})

const openExamine = (row: any) => {
  examineForm.applyId = row.id
  //初审还是终审
  examineForm.auditType = row.processStatus == 10 ? 0 : 1;
  examineShow.value = true
}
const closeExamine = () => {
  examineForm.applyId = undefined
  examineShow.value = false
}
const submitExamine = async () => {
  try {
    await LwBookOutApplyApi.outApplyExamine(examineForm)
    await getList()
    message.notifySuccess("审核完成")
    closeExamine();
  } finally {
  }
}
/** 书籍列表 */
const booksShow = ref(false)
const bookLoading = ref(false) // 列表的加载中
const bookList = ref<LwBookVO[]>([]) // 列表的数据
const bookQueryParams = reactive({
  id: undefined,
})
const openBooks = (row: any) => {
  bookQueryParams.id = row.id
  bookList.value = row.books
  booksShow.value = true
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    queryParams.processList = [-1,100]
    const data = await LwBookOutApplyApi.getLwBookOutApplyPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 导入操作 */
const importFormRef = ref()
const handleImport = () => {
  importFormRef.value.open()
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await LwBookOutApplyApi.deleteLwBookOutApply(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {
  }
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    queryParams.processList = [-1,100]
    const data = await LwBookOutApplyApi.exportLwBookOutApply(queryParams)
    download.excel(data, '书籍漂出.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 搜索用户 */
const searchUsers = async (query: string) => {
  if (!query) {
    userList.value = []
    return
  }
  try {
    userLoading.value = true
    const data = await MemberUserApi.getUserPage({
      pageNo: 1,
      pageSize: 10,
      nickname: query
    })
    userList.value = data.list
  } catch (error) {
    console.error('搜索用户失败:', error)
  } finally {
    userLoading.value = false
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>
